<template>
	<view class="container">
		<!-- Form Content -->
		<view class="form-content">
			<!-- Weight Value -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text class="text-black">体重:</text>
				</view>
				<view class="input-wrapper" @tap="showWeightPicker">
					<text :class="weight ? 'selected-value' : 'placeholder'">{{ weight ? weight + ' kg' : '请选择体重' }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- Weight Picker Popup -->
			<uni-popup ref="weightPopup" type="bottom">
				<view class="picker-container">
					<view class="picker-header">
						<text @tap="hidePicker" style="color: #c8cacf;">取消</text>
						<view class="title">
							<text class="selected-value text-blod"
								style="font-weight: 600;font-size: 34rpx;">{{ tempIntegerPart }}.{{ tempDecimalPart }} kg</text>
						</view>
						<text @tap="confirmPicker" style="color: #4cd080;">确定</text>
					</view>
					<view class="picker-content">
						<picker-view
							:value="[integerRange.indexOf(tempIntegerPart), decimalRange.indexOf(tempDecimalPart)]"
							@change="onWeightChange" class="picker-view">
							<picker-view-column>
								<view class="picker-item" v-for="item in integerRange" :key="item">
									{{ item }}
								</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="item in decimalRange" :key="item">
									.{{ item }}
								</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
			</uni-popup>

			<!-- Height Value -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text class="text-black">身高:</text>
				</view>
				<view class="input-wrapper" @tap="showHeightPicker">
					<text :class="height ? 'selected-value' : 'placeholder'">{{ height ? height + ' CM' : '请选择身高' }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- Height Picker Popup -->
			<uni-popup ref="heightPopup" type="bottom">
				<view class="picker-container">
					<view class="picker-header">
						<text @tap="hideHeightPicker" style="color: #c8cacf;">取消</text>
						<view class="title">
							<text class="selected-value text-blod"
								style="font-weight: 600;font-size: 34rpx;">{{ tempHeight }} CM</text>
						</view>
						<text @tap="confirmHeightPicker" style="color: #4cd080;">确定</text>
					</view>
					<view class="picker-content">
						<view class="height-picker-wrapper">
							<picker-view
								:value="[heightRange.indexOf(tempHeight)]"
								@change="onHeightChange" class="height-picker-view">
								<picker-view-column>
									<view class="picker-item" v-for="item in heightRange" :key="item">
										{{ item }}
									</view>
								</picker-view-column>
							</picker-view>
							<text class="height-unit">CM</text>
						</view>
					</view>
				</view>
			</uni-popup>


			<!-- Measurement Time -->
			<view class="form-item">
				<view class="label">
					<text class="required">*</text>
					<text class="text-black">测量时间</text>
				</view>
				<view class="input-wrapper" @tap="showTimePicker">
					<text
						:class="selectedTime ? 'selected-value' : 'placeholder'">{{ selectedTime || '请选择测量时间' }}</text>
					<text class="arrow">></text>
				</view>
			</view>

			<!-- Time Picker Popup -->
			<uni-popup ref="timePopup" type="bottom">
				<view class="picker-container">
					<view class="picker-header">
						<text @tap="hideTimePicker" style="color: #c8cacf;">取消</text>
						<view class="title">
							<text class="selected-value text-blod"
								style="font-weight: 600;font-size: 34rpx;">{{ formatTempTime }}</text>
						</view>
						<text @tap="confirmTimePicker" style="color: #4cd080;">确定</text>
					</view>
					<view class="picker-content">
						<picker-view :value="[yearIndex, monthIndex, dayIndex, hourIndex, minuteIndex, secondIndex]"
							@change="onTimeChange" class="picker-view">
							<picker-view-column>
								<view class="picker-item" v-for="year in years" :key="year">
									{{ year }}年
								</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="month in months" :key="month">
									{{ month }}月
								</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="day in days" :key="day">
									{{ day }}日
								</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="hour in hours" :key="hour">
									{{ hour.toString().padStart(2, '0') }}时
								</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="minute in minutes" :key="minute">
									{{ minute.toString().padStart(2, '0') }}分
								</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="second in seconds" :key="second">
									{{ second.toString().padStart(2, '0') }}秒
								</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
			</uni-popup>
		</view>

		<!-- Save Button -->
		<view class="save-button" @tap="saveData">
			保存
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex"
	import {
		uniPopup
	} from '@dcloudio/uni-ui'
	import {
		addWeight,
		queryWeightTypeList
	} from '@/api/healthData/everyWeight.js'

	export default {
		computed: mapGetters(['name', 'id','userId']),
		components: {
			uniPopup
		},
		data() {
			return {
				weight: '',
				height: '',
			integerPart: 60,
			decimalPart: 0,
			tempIntegerPart: 60,
			tempDecimalPart: 0,
			tempHeight: 170,
				integerRange: [],
				decimalRange: [],
				heightRange: [],
				selectedTime: '',
				tempTime: {
					year: new Date().getFullYear(),
					month: new Date().getMonth() + 1,
					day: new Date().getDate(),
					hour: new Date().getHours(),
					minute: new Date().getMinutes(),
					second: new Date().getSeconds()
				},
				years: [],
				months: Array.from({
					length: 12
				}, (_, i) => i + 1),
				days: Array.from({
					length: 31
				}, (_, i) => i + 1),
				hours: Array.from({
					length: 24
				}, (_, i) => i),
				minutes: Array.from({
					length: 60
				}, (_, i) => i),
				seconds: Array.from({
					length: 60
				}, (_, i) => i)
			}
		},
		onLoad(options) {
			this.targetId = options.targetId
			this.queryWeightTypeList()
		},

		computed: {
			yearIndex() {
				return this.years.indexOf(this.tempTime.year)
			},
			monthIndex() {
				return this.months.indexOf(this.tempTime.month)
			},
			dayIndex() {
				return this.days.indexOf(this.tempTime.day)
			},
			hourIndex() {
				return this.hours.indexOf(this.tempTime.hour)
			},
			minuteIndex() {
				return this.minutes.indexOf(this.tempTime.minute)
			},
			secondIndex() {
				return this.seconds.indexOf(this.tempTime.second)
			},
			formatTempTime() {
				const {
					year,
					month,
					day,
					hour,
					minute,
					second
				} = this.tempTime

				const period = hour < 12 ? '上午' : '下午'
				const displayHour = hour % 12 || 12

				return `${period} ${displayHour}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`
			},
			formatSaveTime() {
				const {
					year,
					month,
					day,
					hour,
					minute,
					second
				} = this.tempTime

				return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`
			}
		},
		created() {
			// 生成年份范围（当前年份前后5年）
			const currentYear = new Date().getFullYear()
			for (let i = currentYear - 5; i <= currentYear + 5; i++) {
				this.years.push(i)
			}

			// 生成体重整数部分范围（20-300斤）
			for (let i = 2; i <= 300; i++) {
				this.integerRange.push(i)
			}
			// 生成体重小数部分范围（0.0-0.9）
			for (let i = 0; i <= 9; i++) {
				this.decimalRange.push(i)
			}

			// 生成身高范围（80-250CM）
			for (let i = 30; i <= 250; i++) {
				this.heightRange.push(i)
			}

		},
		methods: {
			navigateBack() {
				uni.navigateBack()
			},
			showWeightPicker() {
				this.tempIntegerPart = this.integerPart;
				this.tempDecimalPart = this.decimalPart;
				this.$refs.weightPopup.open();
			},
			hidePicker() {
				this.$refs.weightPopup.close();
			},
			onWeightChange(e) {
				const [intIndex, decIndex] = e.detail.value;
				this.tempIntegerPart = this.integerRange[intIndex];
				this.tempDecimalPart = this.decimalRange[decIndex];
			},
			confirmPicker() {
				this.integerPart = this.tempIntegerPart;
				this.decimalPart = this.tempDecimalPart;
				this.weight = `${this.integerPart}.${this.tempDecimalPart}`;
				this.hidePicker();
			},
			showHeightPicker() {
				this.tempHeight = this.height || 170;
				this.$refs.heightPopup.open();
			},
			hideHeightPicker() {
				this.$refs.heightPopup.close();
			},
			onHeightChange(e) {
				const [heightIdx] = e.detail.value;
				this.tempHeight = this.heightRange[heightIdx];
			},
			confirmHeightPicker() {
				this.height = this.tempHeight;
				this.hideHeightPicker();
			},
			showTimePicker() {
				if (!this.selectedTime) {
					// 如果没有选择过时间，使用当前时间
					const now = new Date()
					this.tempTime = {
						year: now.getFullYear(),
						month: now.getMonth() + 1,
						day: now.getDate(),
						hour: now.getHours(),
						minute: now.getMinutes(),
						second: now.getSeconds()
					}
				}
				this.$refs.timePopup.open()
			},
			hideTimePicker() {
				this.$refs.timePopup.close()
			},
			onTimeChange(e) {
				const [yearIdx, monthIdx, dayIdx, hourIdx, minuteIdx, secondIdx] = e.detail.value
				this.tempTime = {
					year: this.years[yearIdx],
					month: this.months[monthIdx],
					day: this.days[dayIdx],
					hour: this.hours[hourIdx],
					minute: this.minutes[minuteIdx],
					second: this.seconds[secondIdx]
				}
			},
			confirmTimePicker() {
				this.selectedTime = this.formatTempTime
				this.hideTimePicker()
			},
			saveData() {
				if (!this.weight) {
					uni.showToast({
						title: '请选择体重值',
						icon: 'none'
					});
					return;
				}
				if (!this.height) {
					uni.showToast({
						title: '请选择身高',
						icon: 'none'
					});
					return;
				}
				if (!this.selectedTime) {
					uni.showToast({
						title: '请选择测量时间',
						icon: 'none'
					});
					return;
				}

				// 计算BMI
				const weightKg = parseFloat(this.weight) // 斤转公斤
				const heightM = parseFloat(this.height) / 100; // 厘米转米
				const bmi = (weightKg / (heightM * heightM)).toFixed(1);


				const data = {
					measuredTime: this.formatSaveTime,
					weight: this.weight,
					height: this.height,
					bmi: bmi,
					sourceType: '1',
					sourceName: '手工录入',
					userId: this.$store.state.user.userId
				}
				data.measuredType = this.measuredType
				console.log(data)
				addWeight(data).then(res => {
					uni.navigateTo({
						url: `/subPackage_1/pages/index/healthData/weight-success?weight=${encodeURIComponent(this.weight)}&height=${encodeURIComponent(this.height)}&measuredTime=${encodeURIComponent(this.selectedTime)}&id=${res.data}`
					})
				}).catch(err => {
					console.error('添加体重失败:', err);
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				});
			},

			queryWeightTypeList() {
				queryWeightTypeList({
					targetId: this.targetId
				}).then(res => {
					this.measuredType = res.data && res.data.length ? res.data[0].value : ''
					console.log('体重类型列表:', res.data)
				}).catch(err => {
					console.error('获取体重类型失败:', err)
				})
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #fff;
		padding-top: 20px;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.back-icon,
	.more-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.title {
		font-size: 32rpx;
		font-weight: 500;
	}

	.form-content {
		background-color: #fff;
		padding: 0 30rpx;
	}

	.form-item {
		padding: 30rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #fbfbfd;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
	}

	.label {
		display: flex;
		align-items: center;
		margin-bottom: 0;
		min-width: 160rpx;
	}

	.required {
		color: #ff4d4f;
		margin-right: 4rpx;
	}

	.input-wrapper {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		flex: 1;
	}

	.selected-value {
		color: #333;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 100%;
	}

	.placeholder {
		color: #999;
	}

	.arrow {
		color: #999;
		font-size: 24rpx;
	}

	.save-button {
		position: fixed;
		bottom: 40rpx;
		left: 30rpx;
		right: 30rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background-color: #4cd964;
		color: #fff;
		border-radius: 44rpx;
		font-size: 32rpx;
	}

	.picker-container {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;
	}

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 40rpx;
		background-color: #f8f8f8;
		font-size: 32rpx;
	}

	.picker-header .title {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
	}

	.picker-header .title text:first-child {
		color: #666;
		font-size: 28rpx;
	}

	.picker-header .selected-value {
		color: #333;
		font-size: 36rpx;
		font-weight: 500;
	}

	.height-picker-wrapper {
		display: flex;
		align-items: center;
		position: relative;
		height: 500rpx;
	}

	.height-picker-view {
		flex: 1;
		height: 100%;
	}

	.height-unit {
		position: absolute;
		right: 60rpx;
		top: 50%;
		transform: translateY(-50%);
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
		z-index: 10;
		background: #fff;
		padding: 0 10rpx;
	}

	.picker-header text:first-child,
	.picker-header text:last-child {
		color: #007AFF;
	}

	.picker-content {
		position: relative;
		padding: 20rpx 0 40rpx 0;
		background-color: #fff;
	}

	.picker-view {
		width: 100%;
		height: 500rpx;
	}

	.picker-item {
		line-height: 80rpx;
		text-align: center;
		font-size: 36rpx;
		color: #333;
		font-weight: 400;
	}
</style>
